package com.weiter.quartz.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.weiter.common.core.core.page.PageQuery;
import com.weiter.quartz.domain.SysJobLog;
import com.weiter.quartz.mapper.SysJobLogMapper;
import com.weiter.quartz.service.ISysJobLogService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * 定时任务调度日志
 * @author weiter
 */
@Service
public class SysJobLogServiceImpl extends ServiceImpl<SysJobLogMapper, SysJobLog> implements ISysJobLogService {

    @Resource
    private SysJobLogMapper jobLogMapper;

    /**
     * 查询定时任务调度日志分页列表
     * @param query     定时任务调度日志信息
     * @param pageQuery 分页查询信息
     * @return 定时任务调度日志分页列表
     */
    @Override
    public Page<SysJobLog> selectJobLogPage(SysJobLog query, PageQuery pageQuery) {
        LambdaQueryWrapper<SysJobLog> lqw = buildQueryWrapper(query);
        return baseMapper.selectPage(pageQuery.build(), lqw);
    }

    /**
     * 查询定时任务调度日志列表
     * @param sysJobLog 定时任务调度日志信息
     * @return 定时任务调度日志列表
     */
    @Override
    public List<SysJobLog> selectJobLogList(SysJobLog sysJobLog) {
        LambdaQueryWrapper<SysJobLog> lqw = buildQueryWrapper(sysJobLog);
        return baseMapper.selectList(lqw);
    }

    /**
     * 清空任务日志
     */
    @Override
    public void cleanJobLog() {
        jobLogMapper.cleanJobLog();
    }

    private LambdaQueryWrapper<SysJobLog> buildQueryWrapper(SysJobLog query) {
        Map<String, Object> params = query.getParams();
        LambdaQueryWrapper<SysJobLog> lqw = Wrappers.lambdaQuery();
        lqw.like(StrUtil.isNotBlank(query.getJobName()), SysJobLog::getJobName, query.getJobName());
        lqw.eq(StrUtil.isNotBlank(query.getJobGroup()), SysJobLog::getJobGroup, query.getJobGroup());
        lqw.like(StrUtil.isNotBlank(query.getInvokeTarget()), SysJobLog::getInvokeTarget, query.getInvokeTarget());
        lqw.eq(StrUtil.isNotBlank(query.getStatus()), SysJobLog::getStatus, query.getStatus());
        lqw.between(params.get("beginTime") != null && params.get("endTime") != null,
                SysJobLog::getCreateTime, params.get("beginTime"), params.get("endTime"));
        lqw.orderByDesc(SysJobLog::getCreateTime);
        return lqw;
    }
}
